import requests
import logging
import os
from typing import Dict, List, Any, Optional
from functools import wraps
import time
import sys
import os

# 添加项目根目录到 Python 路径，以便导入 config
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from config import API_CONFIG
from tools.log_util import INFO, ERROR, WARNING
# from tools.log_util import setup_logging

# 配置日志
# setup_logging()
# logger = logging.getLogger(__name__)

def api_timer(func):
    """API 调用计时装饰器"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        result = func(*args, **kwargs)
        end_time = time.perf_counter()
        run_time = end_time - start_time
        INFO.logger.info(f"API 调用 {func.__name__} 完成，耗时: {run_time:.3f} 秒")
        return result
    return wrapper

class VMAPIClient:
    """云天虚拟机 API 客户端"""
    
    def __init__(self, token: str = API_CONFIG['token'], base_url: str = API_CONFIG['base_url']):
        """
        初始化 API 客户端
        
        Args:
            token: API 认证令牌
            base_url: API 基础 URL
        """
        self.headers = {'Authorization': f'Bearer {token}'}
        self.base_url = base_url
        self.session = requests.Session()
        self.default_timeout = API_CONFIG['timeout']['default']
        self.long_timeout = API_CONFIG['timeout']['long']
    
    @api_timer
    def get_total_vm_count(self, emc_id: int) -> int:
        """
        获取指定 EMC ID 下的虚拟机总数
        
        Args:
            emc_id: EMC ID
            
        Returns:
            虚拟机总数
        
        Raises:
            requests.RequestException: 请求异常
            KeyError: 响应格式异常
        """
        try:
            url = f'{self.base_url}/vm/list'
            data = {
                "page": {"no": 1, "size": 10},
                "ecns": [f"{emc_id}"],
                "systemLabels": [],
                "customizeLabels": [],
                "projectIds": [],
                "resourceType": 1,
                "arches": ["X86"]
            }
            
            INFO.logger.info(f"获取 EMC ID {emc_id} 的虚拟机总数")
            response = self.session.post(url=url, headers=self.headers, json=data, timeout=self.default_timeout)
            response.raise_for_status()
            
            result = response.json()
            total = result['body']['total']
            INFO.logger.info(f"EMC ID {emc_id} 的虚拟机总数: {total}")
            
            return total
        except requests.RequestException as e:
            ERROR.logger.error(f"请求异常: {e}")
            raise
        except KeyError as e:
            ERROR.logger.error(f"响应格式异常: {e}")
            raise
    
    @api_timer
    def get_vm_data(self, emc_id: int, page_size: Optional[int] = None) -> Dict[str, Any]:
        """
        获取指定 EMC ID 下的虚拟机数据
        
        Args:
            emc_id: EMC ID
            page_size: 分页大小，如果为 None，则使用总数
            
        Returns:
            虚拟机数据
            
        Raises:
            requests.RequestException: 请求异常
        """
        try:
            # 如果没有指定 page_size，则先获取总数
            if page_size is None:
                page_size = self.get_total_vm_count(emc_id)
            
            url = f'{self.base_url}/vm/list'
            data = {
                "page": {"no": 1, "size": page_size},
                "ecns": [f"{emc_id}"],
                "systemLabels": [],
                "customizeLabels": [],
                "projectIds": [],
                "resourceType": 1,
                "arches": ["X86"]
            }
            
            INFO.logger.info(f"获取 EMC ID {emc_id} 的虚拟机数据，页面大小: {page_size}")
            response = self.session.post(url=url, headers=self.headers, json=data, timeout=self.long_timeout)
            response.raise_for_status()
            
            result = response.json()
            INFO.logger.info(f"成功获取 EMC ID {emc_id} 的虚拟机数据")
            
            return result
        except requests.RequestException as e:
            ERROR.logger.error(f"请求异常: {e}")
            raise
    
    @api_timer
    def get_vm_data_by_ids(self, vmids: List[str]) -> Dict[str, Any]:
        """
        通过 VMID 列表获取虚拟机数据
        
        Args:
            vmids: VMID 列表
            
        Returns:
            虚拟机数据
            
        Raises:
            requests.RequestException: 请求异常
        """
        try:
            url = f'{self.base_url}/vm/list'
            payload = {
                "projectIds": [],
                "page": {"no": 1, "size": len(vmids)},
                "resourceType": 1,
                "arches": ["X86"],
                "orders": [{"field": "updatedAt", "type": "DESC"}],
                "vmids": vmids
            }
            
            INFO.logger.info(f"获取 {len(vmids)} 个虚拟机的数据")
            response = self.session.post(url=url, headers=self.headers, json=payload, timeout=self.default_timeout)
            response.raise_for_status()
            
            result = response.json()
            INFO.logger.info(f"成功获取虚拟机数据")
            
            return result
        except requests.RequestException as e:
            ERROR.logger.error(f"请求异常: {e}")
            raise 